
<style lang="scss" scoped>
.container {
  padding: 16px;
  border: 1px solid #efefef;
  // .upload-demo{
  // 	width: 150px;
  // 	.el-upload {
  // 		display: inline-block;
  // 		text-align: center;
  // 		cursor: pointer;
  // 		outline: none;
  // 	}
  // }
}

.el-select .el-select--small {
  display: block !important;
}
</style>

<!-- 页面布局-->
<template>
  <div class="table">
    <!-- 主体区 -->
    <div class="container">
      <!-- 表单区 -->
      <div class="form-data-box">
        <el-form :model="formBean" :rules="validateRules" ref="form1" label-width="120px" class="ruleForm" style="width: 80%;">
          <el-row>
            <el-col :span="24">
              <el-form-item label="卡商" prop="spNo">
                <v-selectpage data="/rps/sp/?isp=10010&pageRows=10&pageIndex=1" :disabled="readOnly" :params="{isp: '10010'}" :page-rows="10" key-field="spNo" show-field="spName" :selected="formBean.spNo" :result-format="resultFormat" :placeholder="formBean.spName || '请选择'" @values="changeSp" >
								</v-selectpage>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="产品名称" prop="productName">
                <el-input :readonly="readOnly" v-model="formBean.productName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="申请数量" prop="cardNum">
                <el-input :readonly="readOnly" v-model="formBean.cardNum"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="年费扣减数量" prop="yearNum">
                <el-input :readonly="readOnly" v-model="formBean.yearNum"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="追加费扣减数量" prop="addNum">
                <el-input :readonly="readOnly" v-model="formBean.addNum"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 表单区END -->
      <!-- 按钮操作区 -->
      <span slot="footer" class="form-btn-box">
        <el-button v-if="!readOnly" @click="resetForm('form1')">重 置</el-button>
        <el-button v-if="!readOnly" type="primary" @click="submitForm()" v-loading.fullscreen.lock="fullscreenLoading">确 定</el-button>
        <el-button @click="cnacelForm('form1')">取 消</el-button>
      </span>
      <!-- 按钮操作区END -->
    </div>
    <!-- 主体区END -->
  </div>
</template>
<script>
export default {
  data() {
    var validateCardNum = (rule, value, callback) => {
      var zg =  /^[0-9]{1,10}$/; 
      if (!zg.test(value) || Number(value) < 1) {
        callback(new Error("请输入大于0的数字"));
      } else {
        callback();
      }
    }
    return {
      // 提交表单的loading设置标识
      fullscreenLoading: false,
      firstLoadedData: "{}",
      // 新增用户表单信息
      formBean: {
        spNo: "", //卡商
        spName: "", //卡商
        productName: "", //上传图片
        cardNum: "" ,//运营商
        yearNum: "" ,//年费扣减数量
        addNum: "" ,//追加费扣减数量
      },
      // 表单校验规则
      validateRules: {
        spNo: [{ required: true, message: "请选择卡商", trigger: "blur" }],
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        cardNum: [
          { required: true, validator: validateCardNum, trigger: "blur" }
        ]
      },
      //所选记录id
      selectedId: "",
      //事物类型
      actType: "",
      // 表单只读状态
      readOnly: true,
      //字典集
      dicts: {},
      cascaders: {},
      cascaderSelected: {},
    };
  },
  props: {
    sourceData: {
      required: true
    }
  },
  // 进入页面加载数据
  mounted() {
    this.handleInitLoad();
  },
  methods: {
    /**
     * 组件初始化加载
     */
    handleInitLoad() {
      this.initSelectOptoins();
      this.initFormData();
    },

    /**
     * 初始加载字典选项
     */
    initSelectOptoins() {
      this.loadSelectOptoins("sp", {"isp":10010});
    },

    /**
     * 通用定义:下拉字典
     *  @augments dictKind 字典类型
     */
    loadSelectOptoins(dictKind, params) {
      let url = "/rps/" + dictKind + "/";
      this.$axios
      .get(url, {
        params: params,
        headers:{
            operator: this.$util.getLoginer().userid,
            withCredentials: true
        }
      })
      .then(res => {
        let data = res.data;
        if (data.success) {
          this.$set(this.dicts, dictKind, data.data.list);
        } else {
          this.$error( "查询失败" + data.message );
        }
      })
      .catch(err => {
        console.log(err);
      });
    },

    /**
     * 取消返回
     * @augments formName 表单名称
     */
    cnacelForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit("cancel", this.cancelData);
    },
    /**
     * 重置表单
     * @augments formName 表单名称
     */
    resetForm(formName) {
      this.formBean = JSON.parse(this.firstLoadedData);
    },
    /**
     *初始化加载表单数据
     */
    initFormData() {
      this.selectedId = this.sourceData.seleid;
      this.actType = this.sourceData.actType;
      if (this.actType == "view") {
        // 查看状态 标识表单只读
        this.readOnly = true;
      } else if (this.actType == "add") {
        this.readOnly = false;
        //清空修改保存之后数据还存在的情况
        for (var key in this.formBean) {
          this.formBean[key] = "";
        }
      }
      //白卡业务上不支持修改，仅支持新增、查看
      var url = "/rps/cardApplyDetail/";
      if ( this.actType != null &&  this.actType == "view" ) { 
        this.formBean = this.sourceData.data;
        url += this.selectedId + "/";
        this.$axios
          .get(
            url,
            {
              params: {},
              headers: {
                operator: this.$util.getLoginer().userid,
                withCredentials: true
              }
            }
          )
          .then(res => {
            let data = res.data;
            if (data.success) {
              this.formBean = Object.assign({},data.data.list[0]);
              this.firstLoadedData = JSON.stringify(this.formBean);
            } else {
              this.$error(data.message);
            }
          })
          .catch(err => {});
      }
    },

    /**
     * 提交表单
     * @augments formName 表单名称
     */
    submitForm(e) {
      //
      this.$refs["form1"].validate(valid => {
        if (valid) {

          this.$confirm(`<div style="padding-left: 20px;"><div class="fxrow"><div class="fxrow" style="width: 70px;margin-right: 20px;"><div style="margin-right: 2em;">卡</div>商：</div>${this.formBean.spName}</div>
          <div class="fxrow"><div style="width: 70px; margin-right: 20px;">产品名称：</div>${this.formBean.productName}</div>
          <div class="fxrow"><div style="width: 70px; margin-right: 20px;">申请数量：</div>${this.formBean.cardNum}</div></div>`, '将直接提交申请，提交后不可更改，是否继续？', {
            dangerouslyUseHTMLString: true,
            closeOnClickModal: false,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(() => {
            // 表单校验成功
            if (this.actType == "add") {
              var url = "/rps/cardApplyBatch/dataformatNo/01/";
              //
              // 开启提交表单的loading
              this.fullscreenLoading = true;
              let formData = [];
              formData.push(this.formBean);
              this.$axios
                .post(url, formData, {
                  headers: {
                    operator: this.$util.getLoginer().userid,
                    withCredentials: true
                  }
                })
                .then(res => {
                  let data = res.data;
                  // 关闭提交表单的loading
                  this.fullscreenLoading = false;
                  if (data.success) {
                    this.$message({
                      message: "开始生成制卡申请文件，并提交联通，请稍候查询申请单状态。。。",
                      type: "success"
                    });
                    this.$emit("ok", {});
                  } else {
                    this.$error(data.message);
                  }
                })
                .catch(err => {
                  this.fullscreenLoading = false;
                });
            }
          }).catch(() => {
                     
          });
         
        } else {
          // 表单校验失败
          // this.$error("数据校验失败.");
        }
      });
    },
    changeSp(res){
			if(res && res.length > 0){
				let sp = res[0];
				this.$set(this.formBean, "spNo", sp.spNo);
				this.$set(this.formBean, "spName", sp.spName);
			}
		},
    /**
		 * v-selectpage 格式化参数数据
		 */
		resultFormat(resp){
			let data = resp.data;
			 if(data.success){
				return {
					totalRow: data.data ? data.data.count : 0,
					list: data.data ? data.data.list : []
				};
			 } else {
				return {
					totalRow: 0,
					list: []
				};
			 }
		}
  }
};
</script>
